package org.cybergarage.http;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.geed.util.UPnPCipher;

public class SecureHTTPServerThread extends Thread {

	protected SecureHTTPServer secureHttpServer;
	protected Socket sock;
	
	public SecureHTTPServerThread(SecureHTTPServer secureHTTPServer,Socket sock)
	{
		this.secureHttpServer = secureHTTPServer;
		this.sock = sock;
	}
	
	public void run()
	{
		/*
		
		try{
			//start server
			ServerSocket ss = new ServerSocket(4004);
			
			//acepted and read
			Socket s = ss.accept();
			String request = "Host "+s.getInetAddress() + "port "+s.getPort();
			InputStream in = s.getInputStream();
			
		
			byte[] read = new byte[2048];
			int bytes_read;
			String dataStr = null;
			
			bytes_read = in.read(read);
			dataStr = new String (read, 0, bytes_read);
			
			//debug
			request += "data===>"+dataStr;
			System.out.println(dataStr);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		*/
		Socket sock = getSock();
		SecureHTTPServer secureHTTPServer = getSecureHttpServer();
		
		HTTPSocket httpSock = new HTTPSocket(sock);
		if (httpSock.open() == false)
			return;
		SecureHTTPRequest httpReq = new SecureHTTPRequest();
		httpReq.setSocket(httpSock);
		while (httpReq.read() == true) {
			//security
			/*
			//if(UPnPCipher.isCentralize()){
				String encContent = httpReq.getContentString();
				System.out.println("[ENC] Content ===>\n"+httpReq.toString());
				String content = UPnPCipher.decode(encContent);
				httpReq.setContent(content, true);
				System.out.println("\n\n[DEC] Content ===>\n"+httpReq.toString());
			//}
			
			*/
			secureHTTPServer.performRequestListener(httpReq);
			if (httpReq.isKeepAlive() == false)
				break;
		}
		httpSock.close();
		
	}

	public Socket getSock() {
		return sock;
	}

	protected SecureHTTPServer getSecureHttpServer() {
		return secureHttpServer;
	}
}
